<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商机名称" prop="orderId">
        <el-select
          v-model="queryParams.orderId"
          filterable
          clearable
          placeholder="请选择商机"
          size="small"
        >
          <el-option
            v-for="item in searchOrder"
            :key="item.orderId"
            :label="item.orderName"
            :value="item.orderId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户" prop="customerI">
        <el-select
          v-model="queryParams.customerId"
          filterable
          clearable
          placeholder="请选择客户"
          size="small"
        >
          <el-option
            v-for="item in customerList"
            :key="item.customerId"
            :label="item.customerName"
            :value="item.customerId"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="负责人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入负责人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="负责人" prop="userId" v-if="$auth.hasRoleOr(['admin','sdl'])">
        <el-select
          v-model="queryParams.userId"
          placeholder="请选择负责人"
          style="width: 100%"
          filterable
          clearable
        >
          <el-option
            v-for="user in userList"
            :key="user.userId"
            :label="user.userName"
            :value="user.userId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="研发人员" prop="devUserId">
        <el-select
          v-model="queryParams.devUserId"
          placeholder="请选择"
          multiple
          size="small"
          filterable
        >
          <el-option
            v-for="item in devExpertList"
            :key="item.expertId"
            :label="item.expertName"
            :value="item.expertId"
          >
            <span style="float: left">{{ item.expertName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              <dict-tag
                :options="dict.type.crm_expert_type"
                :value="item.expertType"
              />
            </span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="实施人员" prop="opsUserId">
        <el-select
          v-model="queryParams.opsUserId"
          placeholder="请选择"
          multiple
          size="small"
          filterable
        >
          <el-option
            v-for="item in opsExpertList"
            :key="item.expertId"
            :label="item.expertName"
            :value="item.expertId"
          >
            <span style="float: left">{{ item.expertName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              <dict-tag
                :options="dict.type.crm_expert_type"
                :value="item.expertType"
              />
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="项目归属" prop="projectType">
        <el-select
          v-model="queryParams.projectType"
          placeholder="请选择项目归属"
          size="small"
          filterable
        >
          <el-option
            v-for="dict in getGroupData()"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crm:project:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['crm:project:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crm:project:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['crm:project:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="projectList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商机名称" align="center" prop="orderName" />
      <el-table-column label="负责人" align="center" prop="createBy" />
      <el-table-column
        label="客户名称"
        align="center"
        prop="customerName"
        width="120"
      />
      <el-table-column
        label="运维人员"
        align="center"
        prop="opsUserId"
        :formatter="coverUserId"
      />
      <el-table-column
        label="开发人员"
        align="center"
        prop="devUserId"
        :formatter="coverUserId"
      />
      <el-table-column
        label="进度"
        align="center"
        prop="estimateTaskCount"
        :formatter="coverNumber"
      />
      <el-table-column
        label="立项表实施工单"
        align="center"
        prop="opsEstimateTaskCount"
        width="120"
      />
      <el-table-column
        label="立项表开发工单"
        align="center"
        prop="devEstimateTaskCount"
        width="120"
      />
      <el-table-column
        label="实际工单"
        align="center"
        prop="actualTaskCount"
        class-name="clickText"
      >
        <template slot-scope="scope">
          <label @click="toTaskDetail(scope.row.orderId)">{{
            scope.row.actualTaskCount
          }}</label>
        </template>
      </el-table-column>
      <el-table-column label="应收未收" align="center" prop="awaitCollection" />
      <el-table-column label="应付未付" align="center" prop="accountAmt" />
      <el-table-column label="项目归属" align="center" prop="projectType">
        <template slot-scope="scope">
          {{ coverData(scope.row.projectType) }}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="150"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['crm:project:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crm:project:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目对话框 -->
    <el-drawer
      :title="title"
      direction="rtl"
      :visible.sync="visible"
      size="60%"
      append-to-body
      :wrapperClosable="false"
      @close="handleClose"
    >
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
        type="border-card"
        style="margin: 0 20px; min-height: 90vh"
        v-if="!addFlag"
      >
        <el-tab-pane label="项目信息" name="addOrUpdateProject" lazy>
          <addOrUpdateProject
            ref="addOrUpdateProject"
            :customerList="customerList"
            :devExpertList="devExpertList"
            :opsExpertList="opsExpertList"
            @cancel="cancel"
          ></addOrUpdateProject>
        </el-tab-pane>
        <el-tab-pane label="项目合同" name="orderContract" lazy>
          <orderContract
            ref="orderContract"
            :customerList="customerList"
            :orderList="searchOrder"
            :projectInfo="projectInfo"
            @cancel="cancel"
          ></orderContract>
        </el-tab-pane>
        <el-tab-pane label="项目验收" name="acceptanceSheet" lazy>
          <acceptanceSheet
            ref="acceptanceSheet"
            :customerList="customerList"
            :orderList="searchOrder"
            :projectInfo="projectInfo"
            @cancel="cancel"
          ></acceptanceSheet>
        </el-tab-pane>
      </el-tabs>
      <el-card
        v-else
        ref="card"
        class="box-card"
        style="width: 96%; margin: 0 20px; min-height: 90vh"
      >
        <addOrUpdateProject
          ref="addOrUpdateProject"
          :customerList="customerList"
          :devExpertList="devExpertList"
          :opsExpertList="opsExpertList"
          @cancel="cancel"
        ></addOrUpdateProject>
      </el-card>
    </el-drawer>

    <taskDetailsDialog ref="taskDetailsDialog"></taskDetailsDialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject } from "@/api/crm/project";
import { getUserListByStatus } from "@/api/system/user";
import { getExpertList } from "@/api/crm/expert";

import { getCustomerList } from "@/api/crm/customer";

import { getOrderListAll } from "@/api/crm/order";

import taskDetailsDialog from "../components/pc/taskDetailsDialog.vue";

import addOrUpdateProject from "./addOrUpdateProject.vue";
import orderContract from "./orderContract.vue";
import acceptanceSheet from "./acceptanceSheet.vue";
export default {
  name: "Project",
  dicts: ["crm_expert_type"],
  components: { taskDetailsDialog, addOrUpdateProject, orderContract,acceptanceSheet },
  data() {
    return {
      // 遮罩层
      loading: true,
      addFlag: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      visible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        userId: null,
        opsUserId: null,
        devUserId: null,
      },
      // 表单参数
      form: {},
      devExpertList: [],
      opsExpertList: [],
      customerList: [],
      orderList: [],
      searchOrder: [],
      acceptanceSheetList:[],
      activeName: "addOrUpdateProject",
      projectInfo: {},
    };
  },
  created() {
    this.getUserListByStatus()
  },
  methods: {
    getUserListByStatus() {
      getUserListByStatus({ status: "0" }).then((res) => {
        this.userList = res.data;
      });
    },
    coverData(type) {
      switch (type) {
        case "0":
          return "个人";
        case "1":
          return "部门";
        case "2":
          return "小组";
        default:
          return "未知";
      }
    },
    handleClose(done) {
      this.activeName = "addOrUpdateProject";
    },
    getData() {
      this.getList();
      this.getExpertList();
      this.getCustomerList();
      this.getOrderList();
    },
    handleClick(tab, event) {
      this.$nextTick(() => {
        this.$refs[this.activeName].getData();
      });
    },
    coverNumber(row, column, cellValue) {
      row.opsEstimateTaskCount = isNaN(row?.opsEstimateTaskCount)
        ? 0
        : row.opsEstimateTaskCount;

      row.devEstimateTaskCount = isNaN(row?.devEstimateTaskCount)
        ? 0
        : row.devEstimateTaskCount;

      let count = row.opsEstimateTaskCount + row.devEstimateTaskCount;

      const percentage = count === 0 ? 0 : (row.actualTaskCount / count) * 100;
      return Number.isNaN(percentage) || !Number.isFinite(percentage)
        ? "暂无数据"
        : `${percentage.toFixed(2)}%`;
    },
    toTaskDetail(orderId) {
      this.$refs.taskDetailsDialog.open(orderId, null, "1");
    },
    getOrderList() {
      getOrderListAll({}).then((res) => {
        this.searchOrder = res.data;
      });
    },
    coverUserId(row, column, cellValue) {
      if (!cellValue) return "无";
      let userStr = "";
      let arr = cellValue.split(",").map(Number);
      let index = 0;
      let expertList = this.opsExpertList.concat(this.devExpertList);
      arr.forEach((item) => {
        let name = expertList.find(
          (expert) => expert.expertId == item
        )?.expertName;

        userStr += index === 0 ? name : "," + name;
        index++;
      });

      return userStr;
    },
    getExpertList() {
      getExpertList({ expertType: "0" }).then((res) => {
        this.devExpertList = res.data;
      });
      getExpertList({ expertType: "1" }).then((res) => {
        this.opsExpertList = res.data;
      });
    },
    getCustomerList() {
      getCustomerList().then((res) => {
        this.customerList = res.data;
      });
    },
    /** 查询项目列表 */
    getList() {
      this.loading = true;
      let obj = JSON.parse(JSON.stringify(this.queryParams));
      if (this.queryParams.opsUserId) {
        obj.opsUserId = this.queryParams.opsUserId.join(",");
      }
      if (this.queryParams.devUserId) {
        obj.devUserId = this.queryParams.devUserId.join(",");
      }
      listProject(obj).then((response) => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.visible = false;
      this.getList();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        orderId: null,
        customerId: null,
        userId: null,
        opsUserId: null,
        devUserId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.customerId = null;
      this.queryParams.opsUserId = null;
      this.queryParams.devUserId = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.projectId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.addFlag = true;
      this.form.customerId = null;
      this.orderList = [];
      this.visible = true;
      this.title = "添加项目";
      this.$nextTick(() => {
        this.$refs[this.activeName].getProject(null);
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.addFlag = false;
      this.visible = true;
      this.title = "修改项目";
      this.projectInfo = row;
      this.$nextTick(() => {
        this.$refs[this.activeName].getProject(row.projectId);
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$modal
        .confirm('是否确认删除项目编号为"' + projectIds + '"的数据项？')
        .then(function () {
          return delProject(projectIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "crm/project/export",
        {
          ...this.queryParams,
        },
        `project_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>


<style scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
</style>
